/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package socket.chat;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author atsi
 */
public class ChatServerReturn implements Runnable {

    public Socket socket;
    private Scanner input;
    private PrintWriter out;
    public String MESSAGE = "";
    private boolean running = true;

    public ChatServerReturn(Socket s) {
        this.socket = s;
    }

    public boolean isRunning() {
        return running;
    }

    public void setRunning(boolean running) {
        this.running = running;
    }
    
    public void CheckConnection() throws IOException {
        if (!socket.isConnected()) {
            for (int i = 1; i <= ChatServer.ConnectionArrayList.size(); i++) {

                if (ChatServer.ConnectionArrayList.get(i) == socket) {
                    ChatServer.ConnectionArrayList.remove(i);
                }
            }

            for (int i = 1; i <= ChatServer.ConnectionArrayList.size(); i++) {
                Socket temp_socket = ChatServer.ConnectionArrayList.get(i - 1);
                PrintWriter temp_out = new PrintWriter(temp_socket.getOutputStream());
                temp_out.println(temp_socket.getLocalAddress().getHostName() + " disconnected!");
                temp_out.flush();

                System.out.println(temp_socket.getLocalAddress().getHostName() + " disconnected!");
            }
        }

    }

    @Override
    public void run() {
        try {
            try {

                input = new Scanner(socket.getInputStream());
                out = new PrintWriter(socket.getOutputStream());

                while (running) {
                    CheckConnection();
                    if (!input.hasNext()) {
                        return;
                    }

                    MESSAGE = input.nextLine();

                    System.out.println("Cliend said: " + MESSAGE);

                    for (int i = 1; i <= ChatServer.ConnectionArrayList.size(); i++) {
                        Socket temp_socket = ChatServer.ConnectionArrayList.get(i - 1);
                        PrintWriter temp_out = new PrintWriter(temp_socket.getOutputStream());
                        temp_out.println(MESSAGE);
                        temp_out.flush();

                        System.out.println("Send to " + temp_socket.getLocalAddress().getHostName());
                    }

                }
            } finally {
                socket.close();
            }

        } catch (IOException ex) {
            Logger.getLogger(ChatServerReturn.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}
